package com.luca.web.controller.system;

import com.luca.common.annotation.Log;
import com.luca.common.core.controller.BaseController;
import com.luca.common.core.domain.JsonResult;
import com.luca.common.core.domain.entity.SysRole;
import com.luca.common.core.domain.entity.SysUser;
import com.luca.common.core.domain.model.LoginUser;
import com.luca.common.core.page.TableDataInfo;
import com.luca.common.enums.BusinessType;
import com.luca.common.utils.ServletUtils;
import com.luca.common.utils.StringUtils;
import com.luca.common.utils.UserUtils;
import com.luca.common.utils.poi.ExcelUtil;
import com.luca.framework.web.service.TokenService;
import com.luca.system.service.ISysPostService;
import com.luca.system.service.ISysRoleService;
import com.luca.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author luca
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private final ISysUserService userService;

    private final ISysRoleService roleService;

    private final ISysPostService postService;

    private final TokenService tokenService;

    @Autowired
    public SysUserController(ISysUserService userService, ISysRoleService roleService, ISysPostService postService, TokenService tokenService) {
        this.userService = userService;
        this.roleService = roleService;
        this.postService = postService;
        this.tokenService = tokenService;
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public JsonResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public JsonResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return JsonResult.success(message);
    }

    @GetMapping("/importTemplate")
    public JsonResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public JsonResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        Map res = new HashMap();
        List<SysRole> roles = roleService.selectRoleAll();
        res.put("roles", UserUtils.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        res.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            res.put(JsonResult.DATA_TAG, userService.selectUserById(userId));
            res.put("postIds", postService.selectPostListByUserId(userId));
            res.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return JsonResult.success(res);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public JsonResult add(@Validated @RequestBody SysUser user) {
        userService.insertUser(user);
        return JsonResult.success();
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public JsonResult edit(@Validated @RequestBody SysUser user) {
        userService.updateUser(user);
        return JsonResult.success();
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public JsonResult remove(@PathVariable Long[] userIds) {
        userService.deleteUserByIds(userIds);
        return JsonResult.success();
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public JsonResult resetPwd(@RequestBody SysUser user) {
        userService.resetPwd(user);
        return JsonResult.success();
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public JsonResult changeStatus(@RequestBody SysUser user) {
        userService.updateUserStatus(user);
        return JsonResult.success();
    }
}
